<template>
  <app-dialog-form
    :title="title"
    :confirm="handleDialogSubmit"
    @closed="handleDialogClose"
    @open="handleDialogOpen"
  >
    <el-form
      class="el-form--label-top"
      ref="form"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item
        label="名称"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="名称"
        />
      </el-form-item>
      <el-form-item
        label="分类编号"
        prop="key"
      >
        <el-input
          v-model="formData.key"
          placeholder="请输入分类编号"
        />
      </el-form-item>
      <el-form-item
        label="排序"
        prop="paixu"
      >
        <el-input
          v-model="formData.paixu"
          placeholder="请输入项目范围"
        />
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { addCategory } from '@/api/category'
import type { IElForm, IFormItemRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
const title = ref('新增分类')
const form = ref<IElForm | null>(null)
const formLoading = ref(false)

const formData = ref({
  name: '',
  key: '',
  paixu: ''
})

const formRules: IFormItemRule = {
  name: [
    { required: true, message: '请输入分类', trigger: 'blur' }
  ],
  key: [
    { required: false, message: '请输入分类编号', trigger: 'blur' }
  ],
  paixu: [
    { required: false, message: '请输入排序', trigger: 'blur' }
  ]
}

interface EmitType {
  (e: 'update:id', value: number | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitType>()

const handleDialogSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  // if (props.id) {
  // // 编辑
  // } else {
  // 添加管理员
  // }
  const data = await addCategory(formData.value)
  console.log(data)
  emit('success')
  ElMessage.success('保存成功')
}

// 打开表单 加载 数据
const handleDialogOpen = () => {
  formLoading.value = true
  // Promise.all([loadRoles(), loadAdmin()]).finally(() => {
  //   formLoading.value = false
  // })
}

const handleDialogClose = () => {
  emit('update:id', null)
  // 清楚 form 表单 必须包含 form 必须包含 ref="form"
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

</script>

<style lang="scss" scoped>
</style>
